#!/usr/bin/env bash

DOCKER_ARGS="--net=host"

if [[ $OSTYPE == 'darwin'* ]]; then
    PHLARE_URL=${PHLARE_URL:-http://docker.for.mac.localhost:4100}
    DOCKER_ARGS=""
else
    PHLARE_URL=${PHLARE_URL:-http://localhost:4100}
fi

PYRO_URL=$PHLARE_URL/pyroscope
PROMETHEUS_URL=$PHLARE_URL/prometheus

datasource_provisioning="$(mktemp "${TMPDIR:-/tmp}/phlare-provisioning-XXXXXX")"
chmod 0644 "${datasource_provisioning}"
trap 'rm -f "${datasource_provisioning}"' EXIT
cat > "${datasource_provisioning}" <<EOF
apiVersion: 1
datasources:
  - name: Prometheus
    type: prometheus
    url: ${PROMETHEUS_URL}
  - name: Phlare
    type: phlare
    url: ${PHLARE_URL}
    jsonData:
      httpHeaderName1: "X-Scope-OrgID"
    secureJsonData:
      httpHeaderValue1: "anonymous"
EOF

docker run $DOCKER_ARGS --rm \
  --name phlare-grafana \
  -v "${datasource_provisioning}:/etc/grafana/provisioning/datasources/phlare.yaml:ro" \
  -v "$(pwd)"/grafana/phlare-datasource/dist:/var/lib/grafana/plugins/phlare-datasource \
  -v "$(pwd)"/grafana/flamegraph/dist:/var/lib/grafana/plugins/flamegraph \
  -e GF_FEATURE_TOGGLES_ENABLE=flameGraph \
  -e GF_INSTALL_PLUGINS=pyroscope-datasource,pyroscope-panel \
  -e GF_DEFAULT_APP_MODE=development \
  -e GF_AUTH_ANONYMOUS_ENABLED=true \
  -e GF_AUTH_ANONYMOUS_ORG_ROLE=Admin \
  -t -i -p 3000:3000 grafana/grafana:main
